package com.cloudcc.boot.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Optional;

@Slf4j
@Component
public class MultiApiKeyInterceptor implements HandlerInterceptor {

    private final ApiKeyRouter router;

    public MultiApiKeyInterceptor(ApiKeyRouter router) {
        this.router = router;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String uri = request.getRequestURI();
        Optional<ApiKeyConfig> maybeCfg = router.match(uri);
        if (maybeCfg.isEmpty()) {
            // 不在受控路径，放行
            log.debug("uri: {} 不在受控路径，放行", uri);
            return true;
        }
        ApiKeyConfig cfg = maybeCfg.get();

        //读取请求头
        String headerVal = request.getHeader(cfg.getHeader());
        if (headerVal == null || headerVal.trim().isEmpty()) {
            log.debug("uri: {} 缺少请求头: {}", uri, cfg.getHeader());
            return unauthorized(response, "Missing header: " + cfg.getHeader());
        }

        //提取密钥
        String clientKey = headerVal.trim();

        // 校验密钥（支持多密钥）
        if (!cfg.getKeys().contains(clientKey)) {
            log.debug("uri: {} 密钥无效: {}", uri, clientKey);
            return unauthorized(response, "Invalid API Key");
        }
        log.debug("uri: {} 密钥有效，放行", uri);
        return true;
    }

    private boolean unauthorized(HttpServletResponse resp, String msg) throws IOException {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        resp.getWriter().write("{\"error\":\"" + msg + "\"}");
        return false;
    }
}